const Config = require('../config');

// 验证 token 是否失效
const checkTokenInvalid = () => {
  // token 存在并且在有效时间内
  return wx.getStorageSync('token');
}
// 设置请求头
const setRequestHeaders = (isToken = false) => {
  const requestHeader = {
    'Content-Type': 'application/json',
  };
  if (isToken) {
    const token = checkTokenInvalid();
    if (token) {
      requestHeader['Authorization'] = `Bearer ${token}`;
    }
    return { requestHeader, token };
  }
  return { requestHeader };
}
// 是否展示弹窗
const handleIsShow = (isShowToast) => {
  if (isShowToast) {
    wx.showModal({
      title: '您目前没有登录，请先去登录',
      success(res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/login/login'
          });
        }
      }
    });
  } else {
    wx.removeStorageSync('user');
    wx.removeStorageSync('token');
  }
}

// API 请求
const request = (url, method = "GET", params = {}, isToken=false, isShowToast=true) => {  
  return new Promise(function (resolve, reject) {
    const { requestHeader, token } = setRequestHeaders(isToken);
    // 如果需要 token 并且获取失败
    if (isToken && !token) {
      handleIsShow(isShowToast);
      return reject('Token invalid');
    }
    wx.request({
      url: Config.BLOG_HOST + url,
      data: params,
      method: method,
      header: requestHeader,
      success: function (res) {
        if (res.statusCode == 200 || res.statusCode == 201) {
          resolve(res.data);
        } else {
          // 请求的页码大于总页数 不弹窗
          if (res.data.code != 'rest_post_invalid_page_number' && isShowToast) {
            wx.showToast({
              title: res.data.message,
              icon: 'none',
              duration: 1500
            });
          }
          // 获取个人信息，未登录或验证失效的情况，清空本地缓存
          if (!isShowToast) {
            console.log('清空');
            handleIsShow(false);
          }
          reject(res.data);
        }
      },
      fail: function (err) {
        console.log(err);
        reject(err);
      }
    })
  })
}
const get = (url, params = {}, isToken = false, isShowToast = true) => {
  return request(url, "GET", params, isToken, isShowToast);
}
const post = (url, params = {}, isToken = false) => {
  return request(url, "POST", params, isToken);
}
const uploadFile = (url, tempFiles) => {
  wx.showLoading({
    title: '正在上传'
  })
  const promises = tempFiles.map(file => {
    return new Promise(function (resolve, reject) {
      wx.uploadFile({
        url: Config.BLOG_HOST + url, 
        filePath: file.tempFilePath,
        name: 'file',
        header: {
          'Authorization': `Bearer ${checkTokenInvalid()}`, 
          'Content-Type':'image/jpeg,image/png,image/gif'
        },
        success (res){
          // console.log("上传成功:", res);
          const data = JSON.parse(res.data);
          resolve({ success: true, url: data.source_url }); 
        },
        fail(err) {
          // console.error("上传失败:", err);
          resolve({ success: false, url: file.tempFilePath });
        }
      })
    })
  })
  // 等待所有上传完成
  return Promise.all(promises)
  .then(results => {
    // 成功上传的文件
    const successfulUploads = results.filter(result => result.success);
    // 失败文件数量
    const failedUploadsCount = tempFiles.length - successfulUploads.length;
    // 全部成功
    if (failedUploadsCount === 0) {
      wx.showToast({
        title: '上传成功',
        icon: 'success',
        duration: 2000
      })
    } else {
      wx.showToast({
        title: `有${failedUploadsCount}个文件上传失败，请重新上传`,
        icon: 'none',
        duration: 2000
      });
    }
    return successfulUploads;
  })
}
module.exports = {
  get,
  post,
  uploadFile
}